import { login, getInfo, updatePwd } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import defaultSettings from '@/settings'
import { Message } from 'element-ui'

const { rolesMap } = defaultSettings
const { admins, services, clients } = rolesMap

const getDefaultState = () => {
  return {
    token: getToken(),
    userName: '',
    avatar: '',
    realName: '',
    userType: '',
    userTypeName: '',
    userInfo: {},
    roleName: ''
  }
}

const state = getDefaultState()

const getters = {
  defaultPage(state) {
    // admins, services, clients
    // roleName
    if (admins.indexOf(state.roleName) > -1) {
      return '/userManage/userManage'
    }
    if (services.indexOf(state.roleName) > -1) {
      return '/workOrderMg/workOrderMg'
    }
    if (clients.indexOf(state.roleName) > -1) {
      return '/workOrderClient/workOrderClient'
    }
    return '/'
  }
}

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, userName) => {
    state.userName = userName
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  async login({ commit, state, getters }, { data: userInfo, after }) {
    const { userName, password } = userInfo
    const { retData: token, success, msg } = await login({
      userName: userName.trim(),
      password: password
    })
    if (!success) {
      Message.warning(msg)
      return
    }
    commit('SET_TOKEN', token)
    setToken(token)
    const { retData } = await getInfo(token)
    const { roleName } = retData || {}
    state.roleName = roleName
 
    if (after) {
      after(getters.defaultPage)
    }
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { retData } = response

          if (!retData) {
            reject('用户信息获取失败,请重新登录')
          }

          const { userName } = retData || {}
          commit('SET_NAME', userName)
          // commit('SET_AVATAR', avatar)
          state.userInfo = retData || {}
          resolve(retData)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  // 修改密码
  async onUpdatePwd({ commit }, payload) {
    await updatePwd(payload)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
